package com.codingfuture.erp_system.web.controller;

import com.codingfuture.erp_system.dto.PageData;
import com.codingfuture.erp_system.dto.RoleMenuDto;
import com.codingfuture.erp_system.entity.Menu;
import com.codingfuture.erp_system.entity.Role;
import com.codingfuture.erp_system.entity.RoleMenu;
import com.codingfuture.erp_system.service.RoleAuthorityService;
import com.codingfuture.erp_system.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequestMapping("/v2")
@RestController
public class RoleAuthorityController {

    @Autowired
    private RoleAuthorityService roleAuthorityService;

    //角色设置渲染
    @PostMapping("/role_list")
    public Result findByAll(@RequestParam(defaultValue = "1") int page,
                            @RequestParam(defaultValue = "10") int rows) {
        Page<Object> page1 = PageHelper.startPage(page, rows);
        List<Role> list = roleAuthorityService.findByAll();
        PageData<Role> data = new PageData<>(list, page1.getTotal());
        return Result.ok(data);
    }

    //获取权限
    @PostMapping("/role_readRoleMenus")
    public Result findById(int id) {
        List<RoleMenu> list = roleAuthorityService.findById(id);
        List<RoleMenuDto> list1 = roleAuthorityService.findByMenu();
        for (RoleMenuDto roleMenuDto : list1) {
            for (Menu child : roleMenuDto.getChildren()) {
                for (RoleMenu roleMenu : list) {
                    if (child.getId().equals(roleMenu.getMenuUuid())) {
                        child.setChecked(true);
                    }
                }
            }
        }
        return Result.OK(list1);
    }

    //添加权限
    @PostMapping("/role_updateRoleMenus")
    public Result update(@RequestParam("id") Integer roleId, @RequestParam("checkedStr") String menuIds) {
        Boolean result = roleAuthorityService.update(roleId, menuIds);
        return result ? Result.ok() : Result.error(201, "错误");
    }
}
